package com.example.imitation_webchat_demo.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import com.example.imitation_webchat_demo.R;
import com.example.imitation_webchat_demo.event.RegisterEvent;
import com.example.imitation_webchat_demo.model.Resource;
import com.example.imitation_webchat_demo.model.TwoLevelSpinner;
import com.example.imitation_webchat_demo.thread.RegisterRunnable;
import com.example.imitation_webchat_demo.util.AppUtils;
import com.example.imitation_webchat_demo.util.ApplicationUtils;
import com.example.imitation_webchat_demo.util.BPUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import de.greenrobot.event.EventBus;

// 注册页面
public class RegisterActivity extends Activity {
	@ViewInject(R.id.register_username)
	private EditText usernameText;

	@ViewInject(R.id.register_password)
	private EditText passwordText;

	@ViewInject(R.id.register_password_confirm)
	private EditText passwordConfirmText;

	@ViewInject(R.id.register_nickname)
	private EditText nicknameText;

	@ViewInject(R.id.register_email)
	private EditText emailText;

	@ViewInject(R.id.register_sex)
	private Spinner sexSpinner;

	@ViewInject(R.id.register_province_city)
	private TwoLevelSpinner addressSpinner;

	@ViewInject(R.id.register_vertification)
	private EditText vertificationText;

	@ViewInject(R.id.register_vertification_image)
	private ImageView vertificationView;

	private String username;
	private String password;
	private String passwordConfirm;
	private String nickname;
	private String email;
	private String sex;
	private String province;
	private String city;
	private String vertification;
	
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置无标题
		setContentView(R.layout.activity_register);

		ViewUtils.inject(this);
		EventBus.getDefault().register(this);
		initComponent(); // 初始化控件
		
		ApplicationUtils.getInstance().addActivity(this);
	}

	// 初始化控件
	private void initComponent() {
		dialog = new ProgressDialog(this);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setMessage("正在注册，请稍候...");
		ArrayAdapter<CharSequence> sexAdapter = ArrayAdapter
				.createFromResource(this, R.array.sex,
						android.R.layout.simple_spinner_item);
		sexAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sexSpinner.setAdapter(sexAdapter);
		
		AppUtils.setImageResource(vertificationView); // 初始化验证码，在imageview中显示验证码
	}

	// 得到控件里的值
	private void getComponentValues() {
		username = usernameText.getText().toString().trim();
		password = passwordText.getText().toString().trim();
		passwordConfirm = passwordConfirmText.getText().toString().trim();
		nickname = nicknameText.getText().toString().trim();
		email = emailText.getText().toString().trim();
		sex = sexSpinner.getSelectedItem().toString();
		province = addressSpinner.getProvince();
		city = addressSpinner.getCity();
		vertification = vertificationText.getText().toString().trim();
	}

	// 点击返回箭头
	@OnClick(R.id.register_head_back)
	private void back(View view) {
		AppUtils.hideSoftInputWindow(this, usernameText);
		finish();
	}

	// 点击登录按钮
	@OnClick(R.id.register_login_btn)
	private void login(View view) {
		AppUtils.hideSoftInputWindow(this, usernameText);
		Intent intent = new Intent(this, LoginActivity.class);
		startActivity(intent);
	}

	// 点击验证码图片
	@OnClick(R.id.register_vertification_image)
	private void switchImage(View view) {
		AppUtils.setImageResource(vertificationView); // imageview切换验证码
	}

	// 点击注册按钮
	@OnClick(R.id.register_register_btn)
	private void register(View view) {
		getComponentValues();

		AppUtils.hideSoftInputWindow(this, usernameText);
		if (username == null || username.equals("")) {
			AppUtils.showToast(this, "用户名不能为空，请重新输入");
			AppUtils.setFocus(usernameText);
			return;
		}
		if (password == null || password.equals("")) {
			AppUtils.showToast(this, "密码不能为空，请重新输入");
			AppUtils.setFocus(passwordText);
			return;
		}
		if (passwordConfirm == null || passwordConfirm.equals("")) {
			AppUtils.showToast(this, "密码不能为空，请重新输入");
			AppUtils.setFocus(passwordConfirmText);
			return;
		}
		if (nickname == null || nickname.equals("")) {
			AppUtils.showToast(this, "昵称不能为空，请重新输入");
			AppUtils.setFocus(nicknameText);
			return;
		}
		if (email == null || email.equals("")) {
			AppUtils.showToast(this, "邮箱不能为空，请重新输入");
			AppUtils.setFocus(emailText);
			return;
		}
		if (!AppUtils.isCharacterOrDigital(username)) {
			AppUtils.showToast(this, "用户名只能是数字和字母的组成，请重新输入");
			AppUtils.setFocus(usernameText);
			return;
		}
		if (AppUtils.containChineseChar(password)) {
			AppUtils.showToast(this, "密码不能包含中文，请重新输入");
			AppUtils.setFocus(passwordText);
			return;
		}
		if (AppUtils.containChineseChar(passwordConfirm)) {
			AppUtils.showToast(this, "密码不能包含中文，请重新输入");
			AppUtils.setFocus(passwordConfirmText);
			return;
		}
		if (!password.equals(passwordConfirm)) {
			AppUtils.showToast(this, "密码不一致，请重新输入");
			AppUtils.setFocus(passwordText);
			return;
		}
		if (!AppUtils.isEmail(email)) {
			AppUtils.showToast(this, "邮箱格式不正确，请重新输入");
			AppUtils.setFocus(emailText);
			return;
		}
		if (!vertification.equalsIgnoreCase(BPUtils.getInstance().getCode())) {
			AppUtils.showToast(this, "验证码不正确，请重新输入");
			AppUtils.setFocus(vertificationText);
			return;
		}
		if (province.contains("请选择")) {
			province = "";
		}
		if(city.contains("请选择")) {
			city = "";
		}
		AppUtils.setImageResource(vertificationView); // imageview切换验证码
		sendMsgToServer(); // 发送数据到服务器
	}

	// 发送消息到服务器
	private void sendMsgToServer() {
		dialog.show();
		
		List<String> list = new ArrayList<String>();
		list.add(username);
		list.add(password);
		list.add(nickname);
		list.add(email);
		list.add(sex);
		list.add(province);
		list.add(city);
		new Thread(new RegisterRunnable(this, list)).start();
	}

	// 处理注册事件后的返回响应
	public void onEventMainThread(RegisterEvent event) {
		dialog.dismiss();
		
		if (event != null) {
			String result = event.getResult();
			if (result != null) {
				if (result.contains("username exist")) {
					AppUtils.showToast(this, "用户名已存在");
				} else if (result.contains("email exist")) {
					AppUtils.showToast(this, "邮箱已存在");
				} else if(result.contains("fail")) {
					AppUtils.showToast(this, "注册失败，请重试");
				} else{
					AppUtils.showToast(this, "注册成功");
					
					jumpToLoginActivity();     // 跳转到登录页面
				}
			} else {
				AppUtils.showToast(this, Resource.disconnectionTip);
			}
		}
	}
	
	 // 跳转到登录页面
	private void jumpToLoginActivity(){
		Intent intent = new Intent(this, LoginActivity.class);
		intent.putExtra("username", username);
		startActivity(intent);
	}

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		ApplicationUtils.getInstance().removeActivity(this);
		super.onDestroy();
	}
}